package com.capgemini.expense;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import com.capgemini.expense.dao.TokenDao;
import com.capgemini.expense.model.ExpenseContext;

public class TokenUtil {

	public static ExpenseContext accessToken(String token) {
		cleanInvalidTokens();
		ExpenseContext context = new TokenDao().getByToken(token);
		if (context != null) {
			context.setLastAccess(new Date());
			return context;
		}
		return null;
	}

	public static void expireToken(String token) {
		TokenDao tokenDao = new TokenDao();
		ExpenseContext context = tokenDao.getByToken(token);
		if (context != null) {
			tokenDao.delete(context);
		}
	}

	private static void cleanInvalidTokens() {

		Calendar nowPlus30Minutes = new GregorianCalendar();
		nowPlus30Minutes.setTime(new Date());
		nowPlus30Minutes.add(Calendar.MINUTE, -30);
		new TokenDao().clearInvalidTokens(nowPlus30Minutes.getTime());
	}

}
